package com.geeklan.smart.ui.message;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.view.View;
import android.widget.Toast;

import androidx.annotation.UiThread;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.geeklan.base.base.BaseActivity;
import com.geeklan.smart.R;
import com.geeklan.smart.data.model.Message;
import com.geeklan.smart.data.repository.msg.CommonRepository;
import com.geeklan.smart.databinding.ActivityMessageListBinding;
import com.geeklan.smart.ui.message.adapter.MessageListAdapter;
import com.geeklan.smart.ui.viewmodel.common.CommonViewModel;
import com.geeklan.smart.ui.viewmodel.common.CommonViewModelFactory;
import com.geeklan.smart.widget.CustomPopupWindow;
import com.geeklan.smart.widget.GridSpacingItemDecoration;
import com.geeklan.smart.widget.ItemOnClickListener;

import java.util.ArrayList;
import java.util.List;

public class MessageListActivity extends BaseActivity<ActivityMessageListBinding> implements MessageListAdapter.ItemOnClickListener, View.OnClickListener {
    private CommonViewModel mViewModel;
    private MessageListAdapter mAdapter;
    private List<Message> messageList = new ArrayList<>();
    private List<Message> unreadMessageList = new ArrayList<>();
    private List<Message> readMessageList = new ArrayList<>();

    private int limit = 20;//每页多少条
    private int pageRead = 1;//页码
    private int pageUnread = 1;//页码
    private int pageSizeUnread = 1;
    private int pageSizeRead = 1;
    private int unReadCount = 0;
    private int readCount = 0;
    private int type = 0;//0-全部消息 1-空仓提醒 2-设备离线 3-投喂提醒 4-设备故障
    private int readFlag = 0;//0未读 1已读
    private int refreshType = 0;
    private CustomPopupWindow customPopupWindow;

    private void resetParameter() {
        pageRead = 1;
        pageUnread = 1;
        pageSizeUnread = 1;
        pageSizeRead = 1;
        unReadCount = 0;
        readCount = 0;
        refreshType = 0;
        readFlag = 0;
        messageList.clear();
        unreadMessageList.clear();
        readMessageList.clear();
        mAdapter.notifyDataSetChanged();
        mBinding.rbUnreadMessage.setChecked(true);
        mBinding.rbReadMessage.setChecked(false);
    }

    @Override
    protected ActivityMessageListBinding initBinding() {
        return ActivityMessageListBinding.inflate(getLayoutInflater());
    }


    @Override
    protected void initData() {
        mViewModel = new ViewModelProvider(this, new CommonViewModelFactory(new CommonRepository())).get(CommonViewModel.class);

        mViewModel.getMsgListLiveData().observe(this, response -> {
            if (response.getData() != null && !response.getData().isEmpty()) {
                int count = response.getCount();
                messageList.clear();
                if (readFlag == 0) {
                    unReadCount = count;
                    pageSizeUnread = unReadCount % limit > 0 ? (unReadCount / limit) + 1 : unReadCount / limit;
                    unreadMessageList.addAll(response.getData());
                    messageList.addAll(unreadMessageList);
                    mBinding.rbUnreadMessage.setText(getString(R.string.unread_message) + "(" + unReadCount + ")");
                } else if (readFlag == 1) {
                    readCount = count;
                    pageSizeRead = readCount % limit > 0 ? (readCount / limit) + 1 : readCount / limit;
                    readMessageList.addAll(response.getData());
                    messageList.addAll(readMessageList);
                }
                mBinding.rvMessage.postDelayed(() -> mAdapter.notifyDataSetChanged(), 100);
                if (refreshType == 0) mBinding.rvMessage.scrollToPosition(0);
            } else {
                if (readFlag == 0) {
                    unReadCount = 0;
                    mBinding.rbUnreadMessage.setText(getString(R.string.unread_message) + "(" + unReadCount + ")");
                    if(unreadMessageList.isEmpty()){
                        messageList.clear();
                        mAdapter.notifyDataSetChanged();
                    }
                } else if (readFlag == 1) {
                    readCount = 0;
                    if(readMessageList.isEmpty()){
                        messageList.clear();
                        mAdapter.notifyDataSetChanged();
                    }
                }
            }
            isNotData();
            mBinding.smartRefreshLayout.finishRefresh();
            mBinding.smartRefreshLayout.finishLoadMore();
            dismiss();
        });

        mViewModel.getMsgErrorLiveData().observe(this, s -> {
            Toast.makeText(this, s, Toast.LENGTH_SHORT).show();
            mBinding.smartRefreshLayout.finishRefresh();
            dismiss();
        });

        mViewModel.getReadMsgListLiveData().observe(this, response -> {
            if (response != null && response.getCode() == 0) {
                if (isClickReadAll) {
                    type = 0;
                    setTitle(type);
                    resetParameter();
                    mViewModel.getMsgList(limit, pageRead, type, readFlag);
                } else {
                    unReadCount = unReadCount - 1;
                    mBinding.rbUnreadMessage.setText(getString(R.string.unread_message) + "(" + unReadCount + ")");
                }
            }
            dismiss();
        });

        mViewModel.getReadMsgErrorLiveData().observe(this, s -> {
            Toast.makeText(this, s, Toast.LENGTH_SHORT).show();
            dismiss();
        });
    }

    private void isNotData(){
        if(messageList.isEmpty()){
            mBinding.llNotData.setVisibility(View.VISIBLE);
            mBinding.rvMessage.setVisibility(View.GONE);
        }else {
            mBinding.llNotData.setVisibility(View.GONE);
            mBinding.rvMessage.setVisibility(View.VISIBLE);
        }
    }

    @Override
    protected void initView() {
        mBinding.ivMessageType.setOnClickListener(this);
        mBinding.rbReadMessage.setOnClickListener(this);
        mBinding.rbUnreadMessage.setOnClickListener(this);
        mBinding.ivBack.setOnClickListener(v -> finish());
        mBinding.ivClear.setOnClickListener(v -> {
            isClickReadAll = true;
            loading();
            mViewModel.readMsg(0, type);
        });

        mAdapter = new MessageListAdapter(this, messageList);
        mAdapter.setItemOnClickListener(this);
        mBinding.rvMessage.setLayoutManager(new LinearLayoutManager(this));
        mBinding.rvMessage.addItemDecoration(new GridSpacingItemDecoration(10));
        mBinding.rvMessage.setAdapter(mAdapter);

        mBinding.smartRefreshLayout.setOnRefreshListener(refreshLayout -> {
            readMessageList.clear();
            unreadMessageList.clear();
            refreshType = 0;
            if (readFlag == 0) {
                pageUnread = 1;
            } else if (readFlag == 1) {
                pageRead = 1;
            }
            mViewModel.getMsgList(limit, readFlag == 0 ? pageUnread : pageRead, type, readFlag);
        });
        mBinding.smartRefreshLayout.setOnLoadMoreListener(refreshLayout -> {
            refreshType = 1;
            if ((readFlag == 0 ? pageUnread : pageRead) < (readFlag == 0 ? pageSizeUnread : pageSizeRead)) {
                if (readFlag == 0) {
                    pageUnread++;
                } else if (readFlag == 1) {
                    pageRead++;
                }
                mViewModel.getMsgList(limit, readFlag == 0 ? pageUnread : pageRead, type, readFlag);
            } else {
                mBinding.smartRefreshLayout.finishLoadMore();
                Toast.makeText(this, R.string.not_more_data, Toast.LENGTH_SHORT).show();
            }
        });
        mBinding.smartRefreshLayout.autoRefresh();
    }

    private boolean isClickReadAll = false;

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == mBinding.rbReadMessage.getId()) {
            if (mBinding.rbReadMessage.isChecked()) {
                refreshType = 0;
                readFlag = 1;
                if (readMessageList.isEmpty()) {

                    pageUnread = 1;
                    loading();
                    mViewModel.getMsgList(limit, pageUnread, type, readFlag);
                } else {
                    messageList.clear();
                    messageList.addAll(readMessageList);
                    mAdapter.notifyDataSetChanged();
                }
                isNotData();
            }
        } else if (id == mBinding.rbUnreadMessage.getId()) {
            if (mBinding.rbUnreadMessage.isChecked()) {
                refreshType = 0;
                readFlag = 0;
                if (unreadMessageList.isEmpty()) {
                    pageRead = 1;
                    loading();
                    mViewModel.getMsgList(limit, pageRead, type, readFlag);
                } else {
                    messageList.clear();
                    messageList.addAll(unreadMessageList);
                    mAdapter.notifyDataSetChanged();
                }
                isNotData();
            }
        } else if (id == mBinding.ivMessageType.getId()) {
            customPopupWindow = new CustomPopupWindow(this, t -> {
                //0-全部消息 1-空仓提醒 2-设备离线 3-投喂提醒 4-设备故障
                type = t;
                setTitle(type);
                loading();
                resetParameter();
                mViewModel.getMsgList(limit, pageRead, type, readFlag);
            });
            customPopupWindow.showAtLocation(v, type);
        }
    }

    public void setTitle(int type) {
        switch (type) {
            case 0:
                mBinding.tvTitle.setText("全部消息");
                break;
            case 1:
                mBinding.tvTitle.setText("空仓提醒");
                break;
            case 2:
                mBinding.tvTitle.setText("设备离线");
                break;
            case 3:
                mBinding.tvTitle.setText("投喂提醒");
                break;
            case 4:
                mBinding.tvTitle.setText("设备故障");
                break;
        }
    }

    @Override
    protected void onApplyWindowInsets() {
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            getWindow().setStatusBarColor(Color.WHITE);
            return insets;
        });
    }

    @Override
    public void networkStatus(boolean isConnected) {

    }

    @Override
    public void networkType(int type) {

    }

    @Override
    public void read(int position) {
        isClickReadAll = false;
        Message message = messageList.get(position);
        message.setReadFlag(1);
        messageList.remove(position);
        for (Message m : unreadMessageList) {
            if (m.getId() == message.getId()) {
                unreadMessageList.remove(m);
                break;
            }
        }
        mAdapter.notifyDataSetChanged();
        loading();
        mViewModel.readMsg(message.getId(), type);
    }

    public static void startActivity(Context context) {
        Intent intent = new Intent(context, MessageListActivity.class);
        context.startActivity(intent);
    }
}